import {
  editInitList,
  initInstructAddressEdit,
  saveInstructAddressEdit
} from '@/services/api/api-instruct-address';
import { trimStr } from '@/utils/tool';
import { MobileOutlined, TeamOutlined } from '@ant-design/icons';
import { DrawerForm, ProFormInstance, ProFormText } from '@ant-design/pro-form';
import { useAccess } from '@umijs/max';
import type { TreeDataNode } from 'antd';
import { Alert, Button, Input, message, Space, Spin, Tag, Tree } from 'antd';
import { DataNode } from 'antd/es/tree';
import { useMemo, useRef, useState } from 'react';
import './index.less';
interface EditAddressProps {
  id: string | undefined;
  name: string;
  onSave: () => void;
}
const getParentKey = (key: React.Key, tree: TreeDataNode[]): React.Key => {
  let parentKey: React.Key;
  for (let i = 0; i < tree.length; i++) {
    const node = tree[i];
    if (node.children) {
      if (node.children.some((item) => item.key === key)) {
        parentKey = node.key;
      } else if (getParentKey(key, node.children)) {
        parentKey = getParentKey(key, node.children);
      }
    }
  }
  return parentKey!;
};

const EditAddress: React.FC<EditAddressProps> = ({ id, name, onSave }) => {
  const [expandedKeys, setExpandedKeys] = useState<React.Key[]>([]);
  const [searchValue, setSearchValue] = useState('');
  const [inputValue, setInputValue] = useState('');
  const [autoExpandParent, setAutoExpandParent] = useState(true);
  const [dataTreeAddress, setDataTreeAddressState] = useState<DataNode[]>([]);
  const [dataLoaded, setDataLoaded] = useState(false);
  const [dataCheckTreeContact, setDataCheckTreeContactState] = useState<any>();
  const formRef = useRef<ProFormInstance>();

  const [loading, setLoading] = useState(false);

  const [expandedAll, setExpandedAllState] = useState(false);

  const [addressId, setAddressIdState] = useState<string>();
  const access = useAccess();

  /**
   * 已经添加的用户列表
   */
  const [targetKeys, setTargetKeyss] = useState<string[]>([]);
  const dataList: { key: React.Key; title: string }[] = [];
  const generateList1 = (data: TreeDataNode[]) => {
    for (let i = 0; i < data?.length; i++) {
      const node = data[i];
      const { key, title } = node;
      dataList.push({ key, title });
      if (node.children) {
        generateList1(node.children);
      }
    }
  };
  generateList1(dataTreeAddress);
  /**
   * 预备Tree结构数据
   * @param data
   */
  const keys: React.Key[] = [];
  function readyTreeAddressData(data: Array<UserData.Organization>): any {
    const treeData = new Array();
    console.log(data);
    // 用于存储所有节点的 key
    if (data) {
      data.forEach((val: any, idx, array) => {
        const nodeKey = val.id;
        keys.push(nodeKey); // 收集当前节点的 key
        treeData.push({
          title: val.name,
          key: val.id,
          marks: val.marks,
          accountPhone: val.accountPhone,
          children: readyTreeAddressData(val.children as Array<UserData.Organization>),
        });
      });
      console.log(keys);
      setAutoExpandParent(true);
      //联络人的数据较少可直接展开
      if (access.宣传指令x配置x通讯录修改专员) {
        setExpandedKeys(keys);
      }
    }
    return treeData;
  }

  /**
   * 加载组织树请求网络
   */
  const loadAddressTreeData = async () => {
    try {
      const response = await initInstructAddressEdit();
      if (response.code === 0) {
        setDataTreeAddressState(readyTreeAddressData(response.data));
        setDataLoaded(true);
      }
    } catch (error) {}
  };

  const onExpand = (newExpandedKeys: React.Key[]) => {
    setExpandedKeys(newExpandedKeys);
    setAutoExpandParent(false);
  };

  const onChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const { value } = e.target;
    setInputValue(value);
  };

  const onSearch = (val) => {
    const e = trimStr(val);
    if (e === '') {
      setAutoExpandParent(false);
      setExpandedKeys([]);
    } else {
      const newExpandedKeys = dataList
        .map((item) => {
          if (item.title.indexOf(e) > -1) {
            return getParentKey(item.key, dataTreeAddress);
          }
          return null;
        })
        .filter((item, i, self): item is React.Key => !!(item && self.indexOf(item) === i));
      setExpandedKeys(newExpandedKeys);
      setAutoExpandParent(true);
    }
    setSearchValue(e);
  };

  const treeData = useMemo(() => {
    const loop = (data: TreeDataNode[]): TreeDataNode[] =>
      data.map((item) => {
        console.log(item);
        const strTitle = item.title as string;
        const index = strTitle.indexOf(searchValue);
        const beforeStr = strTitle.substring(0, index);
        const afterStr = strTitle.slice(index + searchValue.length);

        const title =
          index > -1 ? (
            <span>
              {beforeStr}
              <span className="site-tree-search-value">{searchValue} </span>
              {afterStr}
              {item.accountPhone && (
                <span>
                  ( <MobileOutlined />:{item.accountPhone})
                </span>
              )}
              {item?.marks && item?.marks.length > 0 && (
                <Space wrap>
                  {item?.marks.map((item) => (
                    <Tag bordered={false} color="orange">
                      {item}
                    </Tag>
                  ))}
                </Space>
              )}
            </span>
          ) : (
            <>
              <span>{strTitle}</span>
              {item.accountPhone && (
                <span>
                  ( <MobileOutlined />:{item.accountPhone})
                </span>
              )}
              {item?.marks && item?.marks.length > 0 && searchValue && (
                <Space wrap>
                  {item?.marks.map((item) => (
                    <Tag bordered={false} color="orange">
                      {item}
                    </Tag>
                  ))}
                </Space>
              )}
            </>
          );
        if (item.children) {
          return { title, key: item.key, children: loop(item.children) };
        }

        return {
          title,
          key: item.key,
        };
      });

    return loop(dataTreeAddress);
  }, [dataTreeAddress, searchValue]);

  const getCheckedIds = async (id: string) => {
    const res = await editInitList({ id });
    if (res.code === 0) {
      setTargetKeyss(res.data), setDataCheckTreeContactState(res.data);
    }
  };

  return (
    <DrawerForm
      title={id === undefined ? '新增联络人' : <span>{name}</span>}
      key={''}
      trigger={
        id === undefined ? (
          <Button key="button" icon={<TeamOutlined />} type="primary">
            新增联络人
          </Button>
        ) : name === '联络人' ? (
          <Button key="button" icon={<TeamOutlined />}>
            联络人
          </Button>
        ) : (
          <span>{name}</span>
        )
      }
      formRef={formRef}
      autoFocusFirstInput
      drawerProps={{
        size: 'large',
        forceRender: true,
        destroyOnClose: true,
        maskClosable: false,
        width: 1000,
      }}
      onFinish={async (values) => {
        const response = await saveInstructAddressEdit({
          combineIds: targetKeys,
          id: id,
          ...values,
        });

        if (response.code === 0) {
          setTargetKeyss([]);
          message.success('修改成功');
          onSave();
          return true;
        }
      }}
      onOpenChange={(visible) => {
        if (visible) {
          loadAddressTreeData();
          if (id) {
            getCheckedIds(id);
            formRef.current?.setFieldValue('name', name);
          }
        } else {
          setExpandedKeys([]);
          setDataCheckTreeContactState([]);
          setInputValue('');
        }
      }}
    >
      <Alert
        message="可能会影响指令下发，请慎重修改。"
        type="warning"
        closable
        style={{ marginBottom: 10 }}
      />
      <ProFormText
        width="xl"
        name="name"
        label="联络人名称"
        placeholder="请输入联络人名称"
        rules={[{ required: true, message: '这是必填项' }]}
        fieldProps={{
          maxLength: 200,
          allowClear: true,
        }}
      />

      <Spin spinning={!dataLoaded}>
        <div style={{ display: 'flex', flexDirection: 'column' }}>
          <Input.Search
            style={{ marginBottom: 8 }}
            placeholder="输入名称查询"
            onChange={onChange}
            value={inputValue}
            onSearch={onSearch}
            allowClear
          />
          {/* {dataLoaded ? <Tree
          onExpand={onExpand}
          expandedKeys={expandedKeys}
          autoExpandParent={autoExpandParent}
          checkedKeys={dataCheckTreeContact}
          treeData={treeData}
          checkable
          selectable={false}
          // treeData={dataTreeAddress}
          onCheck={(e, info) => {
            console.log(e);
            setTargetKeyss(e),
              setDataCheckTreeContactState(e)
          }}
        /> : <>加载数据中...</>} */}
          {/* <div style={{ textAlign: 'right' }}>
            <Button type='primary' onClick={() => setExpandedAllState(!expandedAll)}>{expandedAll ? '收起' : '展开'}</Button>
          </div> */}
          {id ? (
            dataLoaded &&
            dataCheckTreeContact && (
              <Tree
                onExpand={onExpand}
                expandedKeys={expandedKeys}
                autoExpandParent={autoExpandParent}
                checkedKeys={dataCheckTreeContact}
                treeData={treeData}
                // defaultExpandAll={expandedAll}
                checkable
                selectable={false}
                // treeData={dataTreeAddress}
                onCheck={(checkedKeys, info) => {
                  const { node } = info; // 获取节点信息

                  // 如果当前选择的是父节点，则不进行任何操作  ,只针对指令专员
                  if (
                    node.children &&
                    node.children.length > 0 &&
                    access.宣传指令x配置x通讯录修改专员
                  ) {
                    // 防止父节点的复选框状态变化
                    return;
                  }

                  // 如果选择的是子节点，则更新状态
                  setTargetKeyss(checkedKeys);
                  setDataCheckTreeContactState(checkedKeys);
                }}
              />
            )
          ) : dataLoaded ? (
            <Tree
              onExpand={onExpand}
              expandedKeys={expandedKeys}
              autoExpandParent={autoExpandParent}
              checkedKeys={dataCheckTreeContact}
              treeData={treeData}
              // defaultExpandAll={expandedAll}
              checkable
              selectable={false}
              // treeData={dataTreeAddress}
              onCheck={(e, info) => {
                console.log(e);
                setTargetKeyss(e), setDataCheckTreeContactState(e);
              }}
            />
          ) : (
            <>加载数据中...</>
          )}
        </div>
      </Spin>
    </DrawerForm>
  );
};

export default EditAddress;
